package com.eatme.web.app.customer.controller;

import com.alibaba.fastjson2.JSON;
import com.eatme.web.app.customer.entity.TbUser;
import com.eatme.web.app.customer.service.ITbUserService;
import com.eatme.web.common.vo.AppResponse;
import com.eatme.web.security.domain.vo.RefreshTokenRequest;
import com.eatme.web.util.WeChatUtil;
import com.eatme.web.util.jwt.NimbusJoseJwtUtil;
import com.eatme.web.util.wechat.WXBaseService;
import com.eatme.web.util.wechat.vo.WxBaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.nio.file.AccessDeniedException;
import java.util.Map;

@Controller
public class WeChatController {
    private static final Logger LOG = LoggerFactory.getLogger(WeChatController.class);

    private final ITbUserService iTbUserService;

    private final WXBaseService wxBaseService;

    private final NimbusJoseJwtUtil nimbusJoseJwtUtil;

    public WeChatController(ITbUserService iTbUserService, WXBaseService wxBaseService, NimbusJoseJwtUtil nimbusJoseJwtUtil) {
        this.iTbUserService = iTbUserService;
        this.wxBaseService = wxBaseService;
        this.nimbusJoseJwtUtil = nimbusJoseJwtUtil;
    }

    @GetMapping("/tb/wx/login")
    public AppResponse login(@RequestParam("code") String code) {

        // appid secret js_code grant_type
        WxBaseResponse response = null;
        try {
            response = wxBaseService.jscode2session(code);
            LOG.info("jscode2session result: {}", JSON.toJSONString(response));
        }catch (Exception e) {
            LOG.info("jscode2session result: {}",e.getMessage());
        }

        if (response==null|| StringUtils.isEmpty(response.getOpenId())) {
            return AppResponse.error().message(response.getErrmsg());
        }
        // 查询记录是否存在
        TbUser user = iTbUserService.findByOpenId(response.getOpenId());
        if (user!=null) {
            return  AppResponse.ok().data(response);
        }else {

            TbUser tbUser = iTbUserService.buildTbUser(response);
            //存储
            return AppResponse.ok().data(response);
        }
    }

    @GetMapping("/tb/wx/getAccessToken")
    public AppResponse getAccessToken() throws Exception {
        WxBaseResponse response = wxBaseService.getAccessToken();
        return AppResponse.ok().data(response);

    }

    @PostMapping( "/wx/refresh")
    @ResponseBody
    public AppResponse refreshToken(@RequestHeader(name = "Authorization")String authorization) throws AccessDeniedException {
        String PREFIX = "Bearer ";
        String refreshToken = authorization.replace(PREFIX, "");
        return nimbusJoseJwtUtil.refreshToken(refreshToken);
    }

    @RequestMapping( "/wx/profile")
    @ResponseBody
    public AppResponse info(AbstractAuthenticationToken authentication, @RequestBody Map<String,String> map){
        String decodeData =  WeChatUtil.getDecodeData(map);
        LOG.info("解密后数据: {}",decodeData);
        TbUser user = iTbUserService.findByOpenId(authentication.getPrincipal()+"");
        return AppResponse.ok(user);
    }
}
